import { defineStore } from 'pinia';
import type { AuthState, User, LoginRequest, RegisterRequest } from '@/types/auth';

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    token: null,
    isAuthenticated: false,
    isLoading: false,
  }),

  getters: {
    getUserInfo: (state) => state.user,
    isLoggedIn: (state) => state.isAuthenticated && !!state.token,
  },

  actions: {
    // 初始化认证状态（从localStorage恢复）
    initAuth() {
      const token = localStorage.getItem('auth_token');
      const userStr = localStorage.getItem('auth_user');
      
      if (token && userStr) {
        try {
          const user = JSON.parse(userStr);
          this.token = token;
          this.user = user;
          this.isAuthenticated = true;
        } catch (error) {
          console.error('Failed to parse user data:', error);
          this.clearAuth();
        }
      }
    },

    // 登录
    async login(credentials: LoginRequest) {
      this.isLoading = true;
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 模拟登录成功
        const mockUser: User = {
          id: '1',
          name: 'Test User',
          email: credentials.email,
          avatar: '',
          createdAt: new Date(),
          updatedAt: new Date(),
        };
        
        const mockToken = 'mock_jwt_token_' + Date.now();
        
        this.user = mockUser;
        this.token = mockToken;
        this.isAuthenticated = true;
        
        // 保存到localStorage
        localStorage.setItem('auth_token', mockToken);
        localStorage.setItem('auth_user', JSON.stringify(mockUser));
        
        return { success: true, user: mockUser };
      } catch (error) {
        console.error('Login failed:', error);
        return { success: false, error: 'Login failed' };
      } finally {
        this.isLoading = false;
      }
    },

    // 注册
    async register(userData: RegisterRequest) {
      this.isLoading = true;
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 模拟注册成功
        const mockUser: User = {
          id: '1',
          name: userData.name,
          email: userData.email,
          avatar: '',
          createdAt: new Date(),
          updatedAt: new Date(),
        };
        
        const mockToken = 'mock_jwt_token_' + Date.now();
        
        this.user = mockUser;
        this.token = mockToken;
        this.isAuthenticated = true;
        
        // 保存到localStorage
        localStorage.setItem('auth_token', mockToken);
        localStorage.setItem('auth_user', JSON.stringify(mockUser));
        
        return { success: true, user: mockUser };
      } catch (error) {
        console.error('Registration failed:', error);
        return { success: false, error: 'Registration failed' };
      } finally {
        this.isLoading = false;
      }
    },

    // 登出
    logout() {
      this.clearAuth();
    },

    // 清除认证信息
    clearAuth() {
      this.user = null;
      this.token = null;
      this.isAuthenticated = false;
      localStorage.removeItem('auth_token');
      localStorage.removeItem('auth_user');
    },

    // 更新用户信息
    updateUser(userData: Partial<User>) {
      if (this.user) {
        this.user = { ...this.user, ...userData };
        localStorage.setItem('auth_user', JSON.stringify(this.user));
      }
    },
  },
});